<template>
  <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
</template>

<script>
import { addEmployees } from '@/api/employees'
import { formatExcelDate } from '@/utils/index'
export default {
  name: 'Import',
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      const res = this.transExcel(results)
      //   console.log('header', header)
      //   console.log('results', results)
      //   console.log(res)
      this.indexaddEmployees(res)
    },
    // 中文转为英文
    transExcel(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'

      }

      return data.map(zhObj => {
        const enObj = {}
        const zhKeys = Object.keys(zhObj) // ['姓名', '手机号']

        zhKeys.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enObj[enKey] = formatExcelDate(zhObj[zhKey])
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
        })
        return enObj
      })
    },
    // 批量导入员工函数
    async indexaddEmployees(data) {
      try {
        await addEmployees(data)
        //   console.log('res', res)
        this.$message.success('批量导入成功')
        this.$emit('success')
        this.$router.back()
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>

</style>
